var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var https=require("https");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cheerio=require("cheerio");

var app = express();
app.listen(8066);
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {
        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.get("/Free0",function (req,res) {
//爬虫 freeshadowsocks
    https.get("https://get.freeshadowsocks.me/",function (data) {
        var str="";
        data.on("data",function(chunk){
            str+=chunk;//监听数据响应，拼接数据片段
        });
        var qrchode=[];
        data.on("end",function(){

            var $=cheerio.load(str);
            var list=$('#portfolio');
            list.children('div').each(function (item) {
                var pic = $(this);
                var divdom ="https://get.freeshadowsocks.me/"+pic.find('a').attr('href');
                qrchode.push(divdom);

            });
            res.json({result:qrchode});
        });

    });
});

app.get("/Free1",function (req,res) {
    //爬虫2
    var str="";
    var qrchode=[];
    https.get("https://b.freess.biz/",function (data) {
        data.on("data",function (chunk) {

            str+=chunk;
        });

        data.on("end",function () {

            var $=cheerio.load(str);
            var list=$('#portfolio-preview');
            list.children("div").each(function (item) {
                var divdom = $(this);
                divdom.children("div").each(function (dom){
                    var resh = $(this);
                    var pic = resh.find('a').attr('href');
                    qrchode.push(pic);
                });

            });
            res.json({result:qrchode})
        });

    });
});


app.get("/Free3",function (req,res) {

    var str="";
    var qrchode=[];
    https.get("https://www.lagou.com/jobs/list_java?labelWords=&fromSearch=true&suginput=&labelWords=hot",function (data) {

        data.on("data",function (chunk) {

            str+=chunk;
        });

        data.on("end",function () {

            res.json(str);
        });

    });




});


module.exports = app;
